package com.tinyideatech.wechat.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tinyideatech.common.core.controller.BaseController;
import com.tinyideatech.common.core.entity.ApiResult;
import com.tinyideatech.system.entity.*;
import com.tinyideatech.system.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;

@Controller
@RequestMapping("/wx")
@Api("商城访问页面")
public class WxController extends BaseController {

    @Autowired
    private IMallCarouselService carouselService;
    @Autowired
    private IMallGoodsService goodsService;
    @Autowired
    private IMallCartService cartService;
    @Autowired
    private IMallClassifyService classifyService;
    @Autowired
    private IMallMemberService memberService;
    @Autowired
    private IMallOrderService orderService;
    @Autowired
    private IMallOrderItemService orderItemService;
    @Autowired
    private ICarDeviceService deviceService;
    @Autowired
    private IMallNewsService newsService;
    @Autowired
    private ICarModelService modelService;
    @Autowired
    private IMallCollectionService collectionService;

    @Value("${tinyideatech.host}")
    private String host;

//    @Autowired
//    private WxPayConfig payConfig;

    private static final String USER_ID = "user_id";
    private static final String DEVICE_ID = "device_id";
    private static final String NOTIFY_URL = "/wx/notify/order";

    /**
     * index页面
     *
     * @param session
     * @param deviceId
     * @param map
     * @return 测试使用的参数 userId=1211557834093760514
     */
    @GetMapping("/index")
    @ApiOperation("商城index页面")
    public String index(
            HttpSession session,
            @RequestParam(defaultValue = "") String deviceId,
            ModelMap map
    ) {
        if (session.getAttribute(DEVICE_ID) == null) {
            session.setAttribute(DEVICE_ID, deviceId);
        }
        if (deviceId.equals("")) {
            deviceId = (String) session.getAttribute(DEVICE_ID);
        }
        Long userId = (Long) session.getAttribute(USER_ID);
        List<CarDevice> deviceList = deviceService.list(new QueryWrapper<CarDevice>().eq(DEVICE_ID, deviceId));
        if (deviceList.size() == 0) {
            CarDevice cd = new CarDevice();
            cd.setMemberId(userId);
            cd.setDeviceId(deviceId);
            deviceService.save(cd);
        }
        List<MallNews> newsList = newsService.list();
        List<MallCarousel> carouselList = carouselService.list();
        List<MallGoods> topGoodsList = goodsService.page(new Page<>(0, 6), new QueryWrapper<MallGoods>().orderByDesc("create_time").eq("top", 1).eq("status", "1")).getRecords();
        List<MallGoods> newGoodsList = goodsService.page(new Page<>(0, 10), new QueryWrapper<MallGoods>().orderByDesc("create_time").eq("status", "1")).getRecords();
        map.put("newsList", newsList);
        map.put("carouselList", carouselList);
        map.put("topGoodsList", topGoodsList);
        map.put("newGoodsList", newGoodsList);

        for (MallGoods goods : newGoodsList) {
            if (goods.getKeywords() != null && !goods.getKeywords().equals("")) {
                goods.setKeywordsList(Arrays.asList(goods.getKeywords().split(",")));
            }
        }
        Integer count = cartService.count(new QueryWrapper<MallCart>().eq("user_id", userId));
        map.put("count", count);
        return "wx/index";
    }

    @GetMapping("/classify")
    public String classify(
            ModelMap map,
            HttpSession session
    ) {
        String deviceId = (String) session.getAttribute(DEVICE_ID);
        Long userId = (Long) session.getAttribute(USER_ID);
        if (deviceId == null) {
            return "wx/error";
        }
        List<MallClassify> classifyList = classifyService.list(new QueryWrapper<MallClassify>().eq("status", 1).orderByAsc("sort"));
        map.put("classifyList", classifyList);
        Integer count = cartService.count(new QueryWrapper<MallCart>().eq("user_id", userId));
        map.put("count", count);
        return "wx/classify";
    }

    @GetMapping("/order_info/{id}")
    public String orderInfo(
            @PathVariable("id") Long id,
            ModelMap map,
            HttpSession session
    ) {
        String deviceId = (String) session.getAttribute(DEVICE_ID);
        if (deviceId == null) {
            return "wx/error";
        }
        MallOrder order = orderService.getById(id);
        if (order != null) {
            List<MallOrderItem> orderItemList = orderItemService.list(new QueryWrapper<MallOrderItem>().eq("order_id", order.getOrderId()));
            map.put("orderItemList", orderItemList);
            map.put("order", order);
        }
        return "wx/order_info";
    }

    @GetMapping("/orders")
    public String orders(
            HttpSession session,
            ModelMap map
    ) {
        String deviceId = (String) session.getAttribute(DEVICE_ID);
        Long userId = (Long) session.getAttribute(USER_ID);
        List<MallOrder> orderList = orderService.list(new QueryWrapper<MallOrder>().eq(DEVICE_ID, deviceId).orderByDesc("create_time"));
        for (MallOrder order : orderList) {
            order.setOrderItemList(orderItemService.list(new QueryWrapper<MallOrderItem>().eq("order_id", order.getOrderId())));
        }
        map.put("orderList", orderList);
        Integer count = cartService.count(new QueryWrapper<MallCart>().eq("user_id", userId));
        map.put("count", count);

        List<MallCollection> collectionList = collectionService.list(new QueryWrapper<MallCollection>().eq(USER_ID, userId));
        List<Long> ids = new ArrayList<>();
        for (MallCollection collection : collectionList) {
            ids.add(collection.getGoodsId());
        }
        if (ids.size() > 0) {
            Collection<MallGoods> goodsList = goodsService.listByIds(ids);
            map.put("collectGoodsList", goodsList);
        } else {
            map.put("collectGoodsList", new ArrayList<MallGoods>());
        }
        return "wx/orders";
    }

    @GetMapping("/skip")
    public String skip() {
        return "wx/skip";
    }


    @GetMapping("/pro_info/{id}")
    public String proInfo(
            HttpSession session,
            @PathVariable("id") Long id,
            ModelMap map
    ) {
        Long userId = (Long) session.getAttribute(USER_ID);
        Integer count = cartService.count(new QueryWrapper<MallCart>().eq("user_id", userId));
        map.put("count", count);
        Integer collectCount = collectionService.count(new QueryWrapper<MallCollection>().eq(USER_ID, userId).eq("goods_id", id));
        map.put("collectCount", collectCount);

        MallGoods goods = goodsService.getById(id);
        if (goods != null) {
            if (goods.getSubImages() != null && !goods.getSubImages().equals("")) {
                goods.setImageList(Arrays.asList(goods.getSubImages().split(",")));
            }
            if (goods.getKeywords() != null && !goods.getKeywords().equals("")) {
                goods.setKeywordsList(Arrays.asList(goods.getKeywords().split(",")));
            }
            map.put("goods", goods);
        }
        return "wx/pro_info";
    }

    @ResponseBody
    @PostMapping("/order/add")
    public ApiResult addOrder(
            HttpSession session,
            @RequestParam(required = false, defaultValue = "") Long goodsId
    ) {
        Long userId = (Long) session.getAttribute(USER_ID);
        String deviceId = (String) session.getAttribute(DEVICE_ID);
        MallMember user = memberService.getById(userId);
        if (user == null) {
            error("请先登录！");
        }
        String idStr = "|";
        List<CarModel> modelList = modelService.list(new QueryWrapper<CarModel>().eq(DEVICE_ID, deviceId));
        for (CarModel model : modelList) {
            idStr += model.getModelId() + "|";
        }
        if (goodsId != null && !goodsId.equals("") && idStr.indexOf(goodsId + "") > -1) {
            return error("您已经购买过该车模！");
        }
        MallOrder order = new MallOrder();
        order.setUserId(userId);
        order.setUsername(user.getOpenId());
        orderService.save(order);
        MallOrderItem item = new MallOrderItem();

        MallGoods goods = goodsService.getById(goodsId);
        if (goods != null) {
            item.setGoodsId(goodsId);
            item.setOrderId(order.getOrderId());
            item.setNum(1);
            item.setGoodsImage(goods.getMainImage());
            item.setPrice(goods.getPrice());
            item.setGoodsName(goods.getGoodsName());
        } else {
            return error("商品不存在！");
        }
        order.setSize(1);
        order.setTotalPrice(goods.getPrice());

        order.setDeviceId(deviceId);
        orderService.updateById(order);
        orderItemService.save(item);
        return success(order.getOrderId());
    }

    @ResponseBody
    @PostMapping("/order/del/{id}")
    public ApiResult delOrder(
            @PathVariable("id") Long id
    ) {
        MallOrder order = orderService.getById(id);
        if (order != null && order.getPaymentResult().equals("0")) {
            orderService.removeById(id);
        } else {
            return error("已付款的订单不能删除！");
        }
        return success(order.getOrderId());
    }

    @ResponseBody
    @PostMapping("/goodsByClassify/{id}")
    public ApiResult goodsByClassify(
            @PathVariable("id") Long id
    ) {
        List<MallGoods> newGoodsList = goodsService.list(new QueryWrapper<MallGoods>()
                .eq("classify_id", id).orderByDesc("create_time").eq("status", "1"));
        for (MallGoods goods : newGoodsList) {
            if (goods.getKeywords() != null && !goods.getKeywords().equals("")) {
                goods.setKeywordsList(Arrays.asList(goods.getKeywords().split(",")));
            }
        }
        return success(newGoodsList);
    }

    @ResponseBody
    @PostMapping("/cart/add")
    public ApiResult addCart(
            HttpSession session,
            MallCart cart
    ) {
        Long userId = (Long) session.getAttribute(USER_ID);
        cart.setUserId(userId);
        cart.setQuantity(1);
        if (cart.getGoodsId() == null) {
            return error();
        }
        MallGoods goods = goodsService.getById(cart.getGoodsId());
        if (goods != null) {
            cart.setGoodsName(goods.getGoodsName());
            cartService.save(cart);
            return success(cart.getCartId());
        } else {
            return error();
        }
    }

    @ResponseBody
    @PostMapping("/cart/del/{id}")
    public ApiResult delCart(
            @PathVariable("id") Long id
    ) {
        cartService.remove(new QueryWrapper<MallCart>().eq("cart_id", id));
        return success();
    }

    @ResponseBody
    @PostMapping("/collection/add")
    public ApiResult addCollection(
            HttpSession session,
            MallCollection targetCollection
    ) {
        if (targetCollection.getGoodsId() == null) {
            return error();
        }
        Long userId = (Long) session.getAttribute(USER_ID);
        String deviceId = (String) session.getAttribute(DEVICE_ID);
        List<MallCollection> collectionList = collectionService.list(new QueryWrapper<MallCollection>().eq(USER_ID, userId).eq("goods_id", targetCollection.getGoodsId()));
        if (collectionList.size() > 0) {
            return error("您已经收藏！");
        }
        MallCollection collection = new MallCollection();
        collection.setDeviceId(deviceId);
        collection.setUserId(userId);
        collection.setGoodsId(targetCollection.getGoodsId());
        collectionService.save(collection);
        return success();
    }

    @ResponseBody
    @PostMapping("/collection/del/{id}")
    public ApiResult delCollection(
            HttpSession session,
            @PathVariable("id") Long id
    ) {
        Long userId = (Long) session.getAttribute(USER_ID);
        collectionService.remove(new QueryWrapper<MallCollection>().eq(USER_ID, userId).eq("goods_id", id));
        return success();
    }

    @ResponseBody
    @PostMapping("/cart/modify")
    public ApiResult modifyCart(
            MallCart cart
    ) {
        cartService.updateById(cart);
        return success();
    }

    @GetMapping("/pro_list")
    public String proList(
            @RequestParam(required = false, defaultValue = "") String search,
            ModelMap map
    ) {
        List<MallGoods> goodsList = goodsService.list(new QueryWrapper<MallGoods>()
                .like("goods_name", search).orderByDesc("create_time").eq("status", "1"));
        map.put("goodsList", goodsList);
        return "wx/pro_list";
    }

    @GetMapping("/cart")
    public String cart(
            HttpSession session,
            ModelMap map
    ) {
        Long userId = (Long) session.getAttribute(USER_ID);
//        String deviceId = (String) session.getAttribute(DEVICE_ID);
        if (userId != null) {
            List<MallCart> carts = cartService.list(new QueryWrapper<MallCart>().eq(USER_ID, userId));
            for (MallCart cart : carts) {
                cart.setGoods(goodsService.getById(cart.getGoodsId()));
            }
            map.put("carts", carts);
        }
        return "wx/cart";
    }

    @ResponseBody
    @PostMapping("/checkRepeat")
    public ApiResult submit(
            HttpSession session,
            @RequestParam Long orderId, @RequestParam Long goodsId
    ) {
        String deviceId = (String) session.getAttribute(DEVICE_ID);
        String idStr = "|";
        List<CarModel> modelList = modelService.list(new QueryWrapper<CarModel>()
                .eq(DEVICE_ID, deviceId));
        for (CarModel model : modelList) {
            idStr = idStr.concat(model.getModelId() + "|");
        }
        List<MallOrderItem> orderItemList = orderItemService.list(new QueryWrapper<MallOrderItem>()
                .eq("order_id", orderId));
        boolean repeat = false;
        for (MallOrderItem orderItem : orderItemList) {
            // && !orderItem.getGoodsId().equals("")
            if (orderItem.getGoodsId() != null && idStr.contains(orderItem.getGoodsId() + "")) {
                repeat = true;
                break;
            }
        }
        if (orderItemList.size() == 0 && idStr.contains(goodsId + "")) {
            repeat = true;
        }
        if (repeat) {
//            MallGoods mallGoods = goodsService.getById(goodsId);
            return error("您已经购买过该车模！");
        }
        return success();
    }

    @ResponseBody
    @PostMapping("/order/submit")
    public ApiResult submit(
            HttpSession session,
            @RequestParam(required = false, defaultValue = "") String cartIds
    ) {
        Long userId = (Long) session.getAttribute(USER_ID);
        String deviceId = (String) session.getAttribute(DEVICE_ID);
        MallMember user = memberService.getById(userId);
        if (user == null) {
            return error("请先登录");
        }
        List<String> cartIdList = Arrays.asList(cartIds.split(","));
        Collection<MallCart> carts = cartService.listByIds(cartIdList);
        if (cartIdList.size() == 0) {
            return error("您未选择任何商品！");
        } else {
            String idStr = "|";
            List<CarModel> modelList = modelService.list(new QueryWrapper<CarModel>().eq(DEVICE_ID, deviceId));
            for (CarModel model : modelList) {
                idStr += model.getModelId() + "|";
            }
            for (MallCart ca : carts) {
                if (ca.getGoodsId() != null && idStr.indexOf(ca.getGoodsId() + "") > -1) {
                    return error("您已经购买过该车模！");
                }
            }
        }
        MallOrder order = new MallOrder();
        order.setUserId(userId);
        order.setUsername(user.getOpenId());
        orderService.save(order);

        List<Long> removeCartIds = new ArrayList<>();
        double sum = 0.0;
        Integer quantity = 0;
        if (carts.size() > 0) {
            List<MallOrderItem> orderItemList = new ArrayList<>();
            for (MallCart c : carts) {
                MallOrderItem item = new MallOrderItem();
                MallGoods goods = goodsService.getById(c.getGoodsId());
                if (goods != null) {
                    item.setGoodsId(c.getGoodsId());
                    item.setOrderId(order.getOrderId());
                    item.setGoodsImage(goods.getMainImage());
                    item.setNum(c.getQuantity());
                    item.setPrice(goods.getPrice() * c.getQuantity());
                    item.setGoodsName(goods.getGoodsName());
                    orderItemList.add(item);
                    sum += goods.getPrice() * c.getQuantity();
                    quantity += c.getQuantity();
                }
                removeCartIds.add(c.getCartId());
            }
            order.setTotalPrice(sum);
            order.setDeviceId(deviceId);
            order.setSize(quantity);
            orderService.updateById(order);
            cartService.removeByIds(removeCartIds);
            orderItemService.saveBatch(orderItemList);
        }
        return success(order.getOrderId());
    }

}
